from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import RepositoryService, UserService, CollaboratorService, BookService
from common.result.Result import Result
from common.enum import BaseEnum
from common.const import BaseConstant
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time
from util.redis import Redis

'''
获取用户所有可写的 repository 中的被删除的 book
'''
async def GetRecycleBookList(req: Request):
    try:
        token = req.headers.get("token")
        user = await UserService.getUserByToken(token)
        if user == None:
            return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
        
        # 获取协作的 repository
        collaboratorList = await CollaboratorService.getListByUserId(user.id)
        # Log.debug('collaboratorList', collaboratorList)

        # 获取自己创建的 repository
        selfList = await RepositoryService.getRepositoryListByUserId(user.id)
        # Log.debug('selfList', selfList)

        # 构造 repository id 列表，并去重
        repositoryIdList = []
        repositoryIdList.extend([item.repository_id for item in collaboratorList])
        repositoryIdList.extend([item.id for item in selfList])
        repositoryIdList = list(set([item for item in repositoryIdList]))
        # Log.debug('repositoryIdList', repositoryIdList)

        # 获取 repository id 列表，对应的回收站的 book
        recycleList = await BookService.getRecycleBookListByRepositoryIdList(repositoryIdList)
        # Log.debug('recycleList', recycleList)

        # 获取 repository 列表
        repositoryList = await RepositoryService.getRepositoryListByIdList(repositoryIdList)
        
        # 构造返回值
        res = []
        for item in recycleList:
            tmp = {}
            tmp.update(dict(item))
            for repository in repositoryList:
                tmp.update({
                    "repository": dict(repository)
                })
            res.append(tmp)
        return Result.success(res)
    except Exception as e:
        Log.error('获取 book 的回收站数据异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)
